using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Resources;
using System.Threading;

namespace Rally_Dekstop
{
    public partial class frmFetchTestCases : Form
    {
        private ResourceManager m_ResourceManager = Localizer.getInstance().GetResourceManager();
        private bool dataupdated = false;
        private ArrayList threadResult;
        private string toThreadIDText;
        private string toThreadTypeFinal;
        private object parent = null;
        private frmTestCaseFilters testCaseFilters = null;
        private string filterPriority = "None";
        private string filterLastResult = "None";
        private string filterType = "None";


        public frmFetchTestCases(object listener)
        {
            InitializeComponent();
            parent = listener;

            if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
            {
                this.workproduct_comboBox.Items.Add("Use Case");
                this.workproduct_comboBox.Items.Add("Feature");
                this.workproduct_comboBox.Items.Add("Supplemental Requirement");
                this.workproduct_comboBox.Items.Add("Story");
                this.workproduct_comboBox.Items.Add("Defect");
                this.workproduct_comboBox.Items.Add("Test Folder");
            }
            else if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UserStory")
                {
                    this.workproduct_comboBox.Items.Add("User Story");
                    this.workproduct_comboBox.Items.Add("Test Folder");
                    
                }


            this.MdiParent = Rally_Dekstop.Program.RallyMain;
            this.WindowState = FormWindowState.Normal;
            this.Tag = VisibleFormType.TEST_CASE_VIEWER;
        }

        private void close_button_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gettestcases_button_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.Enabled = false;


                if (listView_testcases.Items.Count > 0)

                    if (MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/DeleteAllRecordsWarning"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        return; 
                int i = 0;
                listView_testcases.Items.Clear();
                lbl_Count.Text = "";
                //IRallyService service = null;
                dataupdated = false;

                ArrayList result = new ArrayList();
          
                string typefinal;
                string type = this.workproduct_comboBox.Text.ToLower();

                if (this.workproduct_comboBox.Text == "User Story")
                {
                    typefinal = "hierarchicalrequirement";
                  //  service = new RallyAPIUserStory(RallyDesk.url); 
                }
                else
                {
                 //  service = new RallyAPIUseCase(RallyDesk.url);
                    string type2 = type.Trim();
                    typefinal = type2.Replace(" ", "");
               
                }
               
                toThreadIDText = this.SR_ID.Text;
                toThreadTypeFinal = typefinal;
                
                Thread toRunService = new Thread(new ThreadStart(ThreadGetTestCases));
                toRunService.Start();

                ((RallyDesk)parent).toolStripStatusLabel.Text = "Fetching Test Cases..";
                ((RallyDesk)parent).ProgressBarMain.Style = ProgressBarStyle.Marquee;
                ((RallyDesk)parent).ProgressBarMain.Visible = true;

                while (toRunService.IsAlive)
                {

                    Application.DoEvents();
                }

                toRunService.Abort();
                ((RallyDesk)parent).ProgressBarMain.Visible = false;
                ((RallyDesk)parent).toolStripStatusLabel.Text = "Ready";

                            
                result = threadResult;
                if (result == null)
                {
                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/ValidWorkProduct"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;

                }
                if (result.Count>0)
                {
                   
                    
                    System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem();
                    string[] NewItem = new string[6];
                    string key;
                    for (i = 0; i < result.Count; i++)
                        {
                            key = RallyDesk.CacheKey + ((TestCase)result[i]).TestRef + ((TestCase)result[i]).ID;
                            if (!RallyDesk.Cache.Contains(key))
                                RallyDesk.Cache.Add(key, result[i]);
                            else
                                RallyDesk.Cache.Edit(key, result[i]);
                             bool shouldAdd = true;
                             if (!filterLastResult.Equals("None") || !filterPriority.Equals("None") || !filterType.Equals("None"))
                            {
                                if (!filterLastResult.Equals("None"))
                                {
                                    if (!((TestCase)(result[i])).LastVerdict.Equals(filterLastResult))
                                    {
                                        shouldAdd = false;
                                    }
                                }
                                if (!filterPriority.Equals("None"))
                                {
                                    if (!((TestCase)(result[i])).Priority.Equals(filterPriority))
                                    {
                                        shouldAdd = false;
                                    }
                                }
                                if (!filterType.Equals("None"))
                                {
                                    if (!((TestCase)(result[i])).Type.Equals(filterType))
                                    {
                                        shouldAdd = false;
                                    }
                                }
                                
                            }

                            if(shouldAdd)
                            {
                                NewItem[0] = ((TestCase)(result[i])).ID;
                                NewItem[1] = ((TestCase)(result[i])).Name;
                                NewItem[2] = string.Empty;
                                NewItem[3] = string.Empty;
                                NewItem[4] = string.Empty;
                                NewItem[5] = Convert.ToString(((TestCase)(result[i])).TestRef);

                                listViewItem1 = new System.Windows.Forms.ListViewItem(NewItem, -1);
                                this.listView_testcases.Items.AddRange(new System.Windows.Forms.ListViewItem[] { listViewItem1 });
                            }
                      }

                    lbl_Count.Text = Convert.ToString(listView_testcases.Items.Count);
                    dataupdated = true;
                    UploadResults_button.Enabled = true;
                    
                    
                }
                else
                {
                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/NoTestCasesInWorkProduct"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    //MessageBox.Show("This " + type + " does not have any test cases..", "Rally Desk");
                    UploadResults_button.Enabled = false;
                }
            }
            
       finally
            {
                this.Enabled = true;
                this.Cursor = Cursors.Default;
            }

        }

        private void ThreadGetTestCases()
        {
            IRallyService service = null;
            if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
            {
                service = new RallyAPIUseCase(RallyDesk.url);
            }
            else
            {
                service = new RallyAPIUserStory(RallyDesk.url);
            }

            threadResult = service.GetTestCasePerWorkProduct(toThreadTypeFinal, toThreadIDText);
        
        }

        private void UploadResults_button_Click(object sender, EventArgs e)
        {
            try
            {
                if (listView_testcases.Items.Count == 0)
                    return;

                string FileName;
                string msConn;
                FileName = null;



                SaveFileDialog op1 = new SaveFileDialog();
                op1.DefaultExt = ".xls";
                op1.Filter = "Excel(*.xls)|*.xls";


                if (op1.ShowDialog() == DialogResult.OK)
                {

                    FileName = op1.FileName;
                    if (System.IO.File.Exists(FileName))
                    {
                        System.IO.File.Delete(FileName);
                    }
                    op1.Dispose();
                    msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FileName + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";

                    //DataViewer NewData = new DataViewer();
                    OleDbConnection conn = new OleDbConnection();
                    conn.ConnectionString = msConn;
                    conn.Open();

                    System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("CREATE TABLE test " + "([TestCaseID] TEXT(50),[Description] LONGTEXT,[Verdict] TEXT(50),[Build] TEXT(50), [Notes] LONGTEXT,[TestCaseRef] TEXT(255))", conn);
                    cmd.ExecuteNonQuery();
                    foreach (ListViewItem tcitem in listView_testcases.Items)
                    {
                        //StringBuilder str = new StringBuilder();
                        //str.Append("INSERT INTO test VALUES ('" + tcitem.SubItems[0].Text.Replace("\"", "\\\"") + "','" + tcitem.SubItems[1].Text.Replace("\"", "&\\\"") + "','','','')");
                        //cmd.CommandText = str.ToString();
                        // cmd.CommandText = ("INSERT INTO test VALUES ('" + tcitem.SubItems[0].Text + "','" + tcitem.SubItems[1].Text + "','','','')");
                        cmd.CommandText = ("INSERT INTO test VALUES ('" + tcitem.SubItems[0].Text.Replace("'", "''") + "','" + tcitem.SubItems[1].Text.Replace("'", "''") + "','" + tcitem.SubItems[2].Text.Replace("'", "''") + "','" + tcitem.SubItems[3].Text.Replace("'", "''") + "','" + tcitem.SubItems[4].Text.Replace("'", "''") + "','" + tcitem.SubItems[5].Text.Replace("'", "''") + "')");
                        cmd.ExecuteNonQuery();

                    }
                    dataupdated = false;

                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/TemplateSaved"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //MessageBox.Show("Template Saved.", "Rally Desk");
                    conn.Close();
                    msConn = null;

                }
            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }
        
        }

        private void SR_ID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                this.gettestcases_button.PerformClick();
            }
        }

        private void SrTestCaseViewer_Load(object sender, EventArgs e)
        {
            if (workproduct_comboBox.Items.Count > 0)
                workproduct_comboBox.SelectedIndex = 0;
        }

    private void SrTestCaseViewer_FormClosing_1(object sender, FormClosingEventArgs e)
        {
            if (dataupdated)
            {
                DialogResult res = new DialogResult();
                res = MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/SaveChanges"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (res == DialogResult.Yes)
                {
                    this.UploadResults_button.PerformClick();
                }
                else if (res == DialogResult.Cancel)
                    e.Cancel = true;

            }
        }

        private void workproduct_comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (workproduct_comboBox.Text == "Test Folder")
                label2.Text = "Name:";
            else
                label2.Text = "ID:";
        }

        private void workproduct_comboBox_SelectedValueChanged(object sender, EventArgs e)
        {

        }

        private void btn_Filters_Click(object sender, EventArgs e)
        {
            if (this.testCaseFilters == null)
                testCaseFilters = new frmTestCaseFilters();
            string[] args = {filterPriority,filterLastResult,filterType};
            string[] newFilters = testCaseFilters.Display(args);
            filterPriority = newFilters[0] as string;
            filterLastResult = newFilters[1] as string;
            filterType = newFilters[2] as string;
        }
    }
}